import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:ycbl/utils/toast_util.dart';

/// 和微信相关的功能，包括登录、分享、支付
/// 微信插件地址：https://github.com/OpenFlutter/fluwx#
class WxUtil{

  factory WxUtil() =>  _getInstance();
  static WxUtil _instance;

  Function(String) _mOnGetCodeSuccess;
  Function _mOnPrepaySuccess;

  static WxUtil _getInstance(){
    if(_instance == null){
      _instance = new WxUtil._init();
    }
    return _instance;
  }

  /// 初始化各种回调
  WxUtil._init(){
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((result) {
      // 登录回调
      if(result is fluwx.WeChatAuthResponse){
        _authResult(result);
      }
      // 支付回调
      if(result is fluwx.WeChatPaymentResponse){
        _payResult(result);
      }
    });
  }

  /// 注册微信api
  registerWxApi() async{
    await fluwx.registerWxApi(
        appId: "wxa7bf8e609a8e1555",
        universalLink: "https://apis.bailitop.com/ycbl/"
    );
  }

  /// 判断手机是否安装微信
  Future<bool> isWeChatInstalled() async{
    return await fluwx.isWeChatInstalled;
  }

  /// 微信登录
  /// 此方法只会返回用户换取 access_token 的 code
  /// 接下来把这个code交个服务端处理登录的逻辑
  sendAuth(Function(String) onGetCodeSuccess){
    _mOnGetCodeSuccess = onGetCodeSuccess;
    fluwx.sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_login")
        .then((value) => print("调起微信登录:$value"));
  }

  /// 处理登录的结果
  _authResult(fluwx.WeChatAuthResponse result){
    switch(result.errCode){
      case 0:
        _mOnGetCodeSuccess(result.code);
        break;
      default:
        ToastUtil.showLongToast(result.errStr);
        break;
    }
  }

  /// 微信支付
  pay(Map<String, dynamic> params,Function onPrepaySuccess){
    _mOnPrepaySuccess = onPrepaySuccess;
    if(params == null || params.isEmpty){
      ToastUtil.showLongToast('请求支付参数错误');
      return;
    }
    fluwx.payWithWeChat(
        appId: params['appId'].toString(),
        partnerId: params['partnerId'].toString(),
        prepayId: params['prepayId'].toString(),
        packageValue: params['packageValue'].toString(),
        nonceStr: params['nonceStr'].toString(),
        timeStamp: params['timeStamp'],
        sign: params['sign'].toString()
    ).then((value) => '调起微信支付:$value');
  }

  /// 微信预支付成功
  /// 接下来需要通过服务器的验证才是真正的成功
  _payResult(fluwx.WeChatPaymentResponse result){
    switch(result.errCode){
      case 0:
        _mOnPrepaySuccess.call();
        break;
      case 1:
        ToastUtil.showLongToast("支付发生未知错误");
        break;
      case 2:
        ToastUtil.showLongToast("取消支付");
        break;
    }
  }
}